<?

include($_SERVER['DOCUMENT_ROOT'].'/includes/functions.inc.php');
include($_SERVER['DOCUMENT_ROOT'].'/config.php');
include($_SERVER['DOCUMENT_ROOT'].'/groups/database.php');

portal_start();

#########################
# Setup Defaults

$sql = array();
$sql['columns'] = 'gridimage_id,title,realname,user_id,grid_reference,comment';
$sql['tables'] = array();

$sql['tables'][] = "p2.gridimage{$id}_bi_view AS gi";
#$sql['tables'][] = "p2.gridimage{$id}_bi AS gi";
#$sql['tables'][] = "INNER JOIN geograph_live.gridimage_search AS gs USING (gridimage_id)";

$sql['wheres'] = array();

$sql['order'] = "created DESC,gridimage_id DESC";
$sql['limit'] = 10;

#########################
# Possiblities and defaults

$view = 'thumbs';
$title = "images recently added to this portal...";
$order = 'added';
$in = 'd';
$opt = '';
$has_hidden = false;

$views = array(
'listing' => '&middot; Full Listing',
'json' => '&middot; JSON',

'thumbs' => '&middot; Thumbnails',
'thumbs2' => '&middot; Thumbnails2',
'text' => '&middot; Plain-Text',
'csv' => 'download as CSV',
);

#########################
# Customise

if (!empty($_GET['view'])) {
	
	if (isset($views[$_GET['view']])) {
		$view = $_GET['view'];
	}
	if ($view == 'csv' || $view == 'json') {
		$sql['columns'] .= ",wgs84_lat,wgs84_long";
		$sql['limit'] = 50;
	} elseif ($view == 'listing') {
		$sql['columns'] .= ",imagetaken,imageclass";
	}
} 

#########################

include($_SERVER['DOCUMENT_ROOT']."/options/default.php");

#########################
# Paging...

if (empty($pgsize)) {$pgsize = $sql['limit'];}

if (!empty($_GET['page'])) {
		
	$page = intval($_GET['page']);
	
	if (empty($page) || $page < 1) {$page = 1;}
		
	$pg = ($page -1)* $pgsize;
	
	$sql['limit'] = "$pg,$pgsize";
} else {
	$page = 1;
	$pg = 0;
}

#########################
# Setup Filters...

if (!empty($_GET['bounds'])) {
	$b = str_replace('Bounds','',$_GET['bounds']);
	$b = str_replace('(','',$b);
	$b = str_replace(')','',$b);
	

	$b = explode(',',$b);

	$sql['wheres'][] = "(`wgs84_long` BETWEEN {$b[1]} AND {$b[3]}) and (`wgs84_lat` BETWEEN {$b[0]} AND {$b[2]})";
	$sql['order'] = "anti_sort";
	
	#if ($view == 'thumbs') {
		$count_query = sqlMakeCountQuery($sql);

		$resultCount = getOne($count_query);
	#} else {
	#	$resultCount = 1;//just to show something. 
	#}
} else {
	
	include($_SERVER['DOCUMENT_ROOT'].'/geograph/sphinxwrapper.class.php'); 

	$CONF['sphinx_host'] = "localhost";
	$CONF['sphinx_port']= 3312;
	$CONF['sphinx_index']= "portalimages";

	if (!empty($_GET['q'])) {

		$q=trim($_GET['q']);

			$q = preg_replace('/\b(day|month|year):/','taken$1:',$q);
			$q = preg_replace('/\b(monthname):/','month:',$q);
			$q = preg_replace('/\b(gridref):/','grid_reference:',$q);
			$q = preg_replace('/\b(category):/','imageclass:',$q);
			$q = preg_replace('/\b(description):/','comment:',$q);
			$q = preg_replace('/\b(name):/','realname:',$q);

		$sphinx = new sphinxwrapper($q);
		$sphinx->pageSize = $pgsize;

		$q = $sphinx->q;
	} else {
		$sphinx = new sphinxwrapper();
		$sphinx->pageSize = $pgsize;

		$q = '';
	}

	$cl = $sphinx->_getClient();
	$cl->setFilter('portal_id',array($portal_id));

	#we cant use filter_setup yet as that doesnt work with sphinx... 		

	if (!empty($_GET['lat'])) {
		$d = empty($_GET['d'])?10:min(20,intval($_GET['d'])); //km

		$cl->SetGeoAnchor('wgs84_lat', 'wgs84_long', deg2rad($_GET['lat']), deg2rad($_GET['long']) );
		$cl->SetFilterFloatRange('@geodist', 0.0, floatval($d*1000));

		$sphinx->setSort("@geodist ASC, @relevance DESC, @id DESC");

		$title = sprintf("Images within %dkm of %.6f,%.6f.",$d,$_GET['lat'],$_GET['long']);
		$extra = sprintf("lat=%.6f&amp;long=%.6f",$_GET['lat'],$_GET['long']);
	}

	$ids = $sphinx->returnIds($page,'portalimages');	

	if (!empty($ids) && count($ids)) {

		$sql['wheres'][] = "gi.gridimage_id IN (".implode(',',$ids).")";
		$sql['order'] = "FIELD(gridimage_id,".implode(',',$ids).")";
	}

	$resultCount = $sphinx->resultCount;
}

$numberOfPages = ceil($resultCount/$pgsize);

#########################
# Display results!

if ($view == 'json') {
	if (!empty($_GET['callback'])) {
		$callback = preg_replace('/[^\w\.-]+/','',$_GET['callback']);
		echo "{$callback}(";
	}
	
	if (!empty($resultCount)) {
		include($_SERVER['DOCUMENT_ROOT'].'/google/JSON.php');

		$query = sqlMakeQuery($sql);

		$data = getAll($query);

		if (!empty($data)) {
			foreach ($data as $idx => $c) {
				$data[$idx]['thumbnail'] = gGUc($c);
			}
			$json = new Services_JSON();
			print $json->encode(array('count'=>$resultCount,'markers'=>&$data));
		} else {
			print "{count:0}";
		}
	} else {
		print "{count:0}";
	}
	
	if (!empty($_GET['callback'])) {
	        echo ");";
	}
	exit;
}

if ($resultCount) {
	$query = sqlMakeQuery($sql);

	$result = queryExecute($query);

	if ($result) {
		print "<p style=clear:left>";
		if ($title) 
			print "<i>$title</i> ";
		if (!$has_hidden) {
			if ($resultCount > $pgsize) {
				printf("Photo %d..%d of %d. ",($pg)+1,min(($pg)+$pgsize,$resultCount),$resultCount);
				
				//todo lat/long hardcoded!
				print "<a href=\"/search.php?$extra\">View more...</a>";
				
			} else {
				print "$resultCount photos.";
			}
		}
		print "</p>";

		include($_SERVER['DOCUMENT_ROOT']."/views/$view.php");

	} else {
		print "<p>Unable to Images to show at this time.</p>";
	}
} else {
	print "<p>No $title</p>";
}



